<template>
  <div>
    <!-- 书籍详情信息界面 -->
    <br /><br /><br /><br />
    <div>
      <el-page-header @back="goBack" content="详情页面"> </el-page-header>
    </div>
    <br />
    <div style="display: flex">
      <!-- 轮播图开始 -->
      <div style="width: 500px; margin-left: 100px; margin-right: 0">
        <el-carousel height="500px">
          <el-carousel-item
            style="height: 100%"
            v-for="(item, index) in previewImage"
            :key="index"
          >
            <el-image
              :preview-src-list="previewImage"
              style="width: 100%; height: 100%"
              :src="item"
              fit="cover"
            ></el-image>
            <!-- fill / contain / cover / none / scale-down -->
          </el-carousel-item>
        </el-carousel>
      </div>
      <!-- 轮播图结束 -->
      <div
        style="width: 500px; background-color: #f4f5f5f4; padding-left: 70px"
      >
        <!-- 详细信息展示开始 -->
        <div>
          <div
            style="color: #f20018; position: absolute; right: 250px; top: 200px"
          >
            <i style="font-size: 20px">￥</i
            ><span style="color: #f20018; font-size: 40px">
              {{ book.price }}
            </span>
          </div>
          <div>
            <el-tooltip :content="book.bookName" placement="top" effect="light"
              ><div style="color: #6e7474; font-size: 30px; font-weight: 700">
                {{ getSubStringBN(book.bookName) }}
              </div>
            </el-tooltip>
          </div>
          <br />
          <div style="color: #6e7474; font-size: 18px; width: 300px">
            <span>作者：</span>{{ book.author }}
          </div>
          <br />
          <div style="color: #6e7474; font-size: smaller">
            <span>书号：</span>{{ book.bookNo }}
          </div>
          <br />
          <div style="color: #6e7474; font-size: 17px">
            <span>类别：</span
            ><span v-for="(item, index) in book.classNames" :key="index"
              >{{ item }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
          </div>
          <br />
          <div style="color: #6e7474; font-size: smaller">
            <span>出版社：</span>{{ book.publish
            }}<span> &nbsp;&nbsp;&nbsp;&nbsp;出版日期：</span
            >{{ book.publicationDate }}
          </div>
          <br />
          <div
            style="
              text-indent: 2em;
              color: #6e7474;
              width: 400px;
              height: 180px;
              line-height: 30px;
              box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.3);
            "
          >
            <el-popover
              :open-delay="300"
              placement="top-start"
              title="简介"
              width="600"
              trigger="hover"
              :content="book.content"
            >
              <div
                style="
                  margin: 5px;
                  padding: 5px;
                  font-size: 15px;
                  font-weight: 300;
                  color: #060708de;
                "
                slot="reference"
              >
                {{ getSubString(book.content) }}
              </div>
            </el-popover>
          </div>
          <div>
            <!-- 购买按钮开始 -->
            <div style="display: flex; position: relative; top: 40px">
              <el-input-number
                v-model="cart.amount"
                :min="1"
                :max="10"
                label="描述文字"
              ></el-input-number>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <div class="btn1" @click="showDialogD">立即购买</div>
              <div class="btn2" @click="addCartt(book.id, book.price)">
                加入购物车
              </div>
            </div>
            <!-- 购买按钮结束 -->
          </div>
        </div>
        <!-- 详细信息展示结束 -->
      </div>
    </div>
    <!-- 直接购买选择地址 -->
    <el-dialog title="选择地址" :visible.sync="dialogVisibleD" width="30%">
      <el-select v-model="addressId">
        <el-option
          v-for="item in address"
          :key="item.id"
          :label="item.detailedAddress"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBuy(book.id, book.price)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getById } from "../api/bookMG"; //书籍表相关请求
import { addCart, buyDirect } from "../api/cartMG"; //购物车表相关请求
import { getAddress } from "@/api/addressMG";
export default {
  name: "DetailesView",
  props: {
    bookId: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      address: [], //地址信息，一进入这个页面就去获取这个用户的所有地址
      addressId: 1, //选择的地址id,默认为获取到的地址的第一个id
      cart: {
        bookId: 0, //书的id
        userId: localStorage.getItem("userId"), //买的人的id
        amount: 1, //买的数量，
        price: "", //总价
      }, //添加进购物车
      previewImage: [], //详情界面点击图片可以预览，在获取单个书籍的时候记得复制给这个数组
      book: {}, //单独的一本书的详情信息，点击某个书籍传入id去后端获取的
      dialogVisibleD: false, //地址选择栏默认关闭--点击直接购买才会显示这个
    };
  },
  methods: {
    showDialogD(id) {
      if (
        localStorage.getItem("userId") == null ||
        localStorage.getItem("userId") == ""
      ) {
        //没登录买不了
        this.$message.error("您还没登录，快去登录吧!");
        localStorage.removeItem("userId");
        this.$router.push("/login");
        return;
      }
      // console.log("111",id)
      this.getAddresses();
      this.cartId = id;
    },
    //立即购买
    async handleBuy(bookId, prices) {
      if (this.address.length == 0) {
        //没地址买不了
        this.$message.error("您还没添加地址，快去个人中心添加地址吧!!!");
        return;
      }
      //单独购买
      this.cart.bookId = bookId;
      this.cart.price = prices * this.cart.amount; //总价等于单价乘以数量
      // console.log(this.addressId,this.cartId);
      // 发送请求
      await buyDirect(this.addressId, this.cart).then((res) => {
        if (res.data.code == 200) this.$message.success(res.data.msg);
        else this.$message.error(res.data.code + "::" + res.data.msg);
      });
      this.dialogVisibleD = false; //购买之后关闭单独购买的dialog
      this.cart.bookId = 0;
      this.cart.price = "";
      this.cart.amount = 1;
    },
    //获取地址
    async getAddresses() {
      if (localStorage.getItem("userId") == null) {
        this.$message.info("未登录");
        location.href = "/login";
        return;
      } else {
        //获取自己的所有地址
        await getAddress(localStorage.getItem("userId")).then((res) => {
          if (res.data.code) {
            if (res.data.data.length != 0) {
              res.data.data.forEach((address) => {
                address.detailedAddress = address.detailedAddress.replace(
                  /%\//g,
                  ""
                );
              });
              this.address = res.data.data;
              this.addressId = res.data.data[0].id;
              console.log(this.address);
              this.dialogVisibleD = true;
              // console.log((res.data.data).id)
            }
            else{
              this.$message({
                showClose:true,
                message:"请先添加地址哦",
                type:"info"
              })
            }
          } else {
            this.$message.error(res.data.code + "::" + res.data.msg);
          }
        });
      }
    },
    getSubStringBN(str) {
      //截取书名前20个字符
      if (str != null && str.length > 14) {
        return str.slice(0, 14) + "...";
      } else {
        return str;
      }
    },
    getSubString(str) {
      //截取简介前20个字符
      if (str != null && str.length > 110) {
        return str.slice(0, 110) + "...";
      } else {
        return str;
      }
    },
    goBack() {
      // console.log("go back");
      this.$emit("detailsGoBack");
    },
    getOne() {
      // 下面这里是这本书的id，根据这个id去查找他的详情信息
      getById(this.bookId).then((res) => {
        if (res.data.code == 200) {
          this.book = res.data.data;
          this.previewImage = res.data.data.imgUrls;
          console.log(res.data.data);
        }
      });
    },
    async addCartt(bookId, prices) {
      //添加进入购物车
      // console.log(bookId);
      if (localStorage.getItem("userId") == null) {
        this.$message.error("未登录");
        this.$router.push("/login");
        return;
      }
      //设置购物车其他选项的值
      //发送请求，将这个数据包装成购物车json，传给后端，后端把这个书籍的购物信息保存在购物表中。
      this.cart.bookId = bookId; //将这本书的id传给购物车对应的的bookId
      this.cart.price = prices * this.cart.amount; //总价等于单价乘以数量
      await addCart(this.cart).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
        } else this.$message.error(res.data.msg);
        this.cart.amount = 1;
        this.cart.bookId = 0;
        this.cart.price = "";
      });
    },
  },
  mounted() {
    this.getOne();
  },
};
</script>
<style>
.btn1,
.btn2 {
  font-weight: 800;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f20018;
  height: 40px;
  width: 100px;
  /* 设置过渡效果，持续时间为2秒 */
  transition: transform 300ms ease;
}
.btn1 {
  border-top-left-radius: 20px; /* 设置左上角的圆角半径 */
  border-bottom-left-radius: 20px; /* 设置左下角的圆角半径 */ /* 同时设置左上角和左下角的圆角半径 */
}
.btn2 {
  background-color: #f88619;
  border-top-right-radius: 20px; /* 设置左上角的圆角半径 */
  border-bottom-right-radius: 20px; /* 设置左下角的圆角半径 */
}
.btn1:hover,
.btn2:hover {
  cursor: pointer;
  transform: scale(1.2);
}
</style>
